package com.proxyhub.repo;

import com.mongodb.DBObject;
import com.proxyhub.model.Proxy;
import com.proxyhub.utils.BeanUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Repository;
import org.springframework.util.CollectionUtils;

import java.awt.print.Pageable;
import java.util.List;

/**
 * Created by linxsh on 2017/6/15.
 */
@Repository
public class ProxyRepoImpl implements ProxyRepo {

    @Autowired
    private MongoTemplate mongoTemplate;


    @Override
    public void save(Proxy proxy) {
        mongoTemplate.save(proxy);
    }

    @Override
    public void save(List<Proxy> proxyList) {
        mongoTemplate.insertAll(proxyList);
    }

    @Override
    public void saveOrUpdate(Proxy proxy) {
        Query query = buildQuery(proxy.getHost(), proxy.getPort());
        DBObject updateObj = BeanUtil.convertToDBObject(proxy);
        mongoTemplate.upsert(query, Update.fromDBObject(updateObj), Proxy.class);
    }

    @Override
    public void saveOrUpdate(List<Proxy> proxyList) {
        for(Proxy proxy : proxyList) {
            saveOrUpdate(proxy);
        }
    }

    @Override
    public List<Proxy> findAll() {
        Query query = Query.query(Criteria.where("valid").is(true));
        return mongoTemplate.find(query, Proxy.class);
    }

    @Override
    public List<Proxy> fetch(int num) {
        Query query = new Query(Criteria.where("valid").is(true));
        query.with(new PageRequest(0, num));
        return mongoTemplate.find(query, Proxy.class);
    }

    @Override
    public void updateValidStatus(Proxy proxy, boolean valid) {
        Query query = buildQuery(proxy.getHost(), proxy.getPort());
        mongoTemplate.updateFirst(query, Update.update("valid", valid), Proxy.class);
    }

    @Override
    public void insertIfNotExist(Proxy proxy) {
        Query query = buildQuery(proxy.getHost(), proxy.getPort());
        boolean exists = mongoTemplate.exists(query, Proxy.class);
        if(!exists) {
            save(proxy);
        }
    }

    @Override
    public void insertIfNotExist(List<Proxy> proxyList) {
        if(!CollectionUtils.isEmpty(proxyList)) {
            for(Proxy proxy: proxyList) {
                Query query = buildQuery(proxy.getHost(), proxy.getPort());
                boolean exists = mongoTemplate.exists(query, Proxy.class);
                if(!exists) {
                    save(proxy);
                }
            }
        }
    }

    private Query buildQuery(String host, int port) {
        return Query.query(Criteria.where("host").is(host).and("port").is(port));
    }


}
